package cn.oi.klittle.era.activity.preview

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.viewpager.widget.ViewPager
import cn.oi.klittle.era.R
import cn.oi.klittle.era.activity.photo.entity.KLocalMedia
import cn.oi.klittle.era.activity.photo.manager.KPictureSelector
import cn.oi.klittle.era.activity.preview.adpater.KPreviewPagerAdapter
import cn.oi.klittle.era.base.KBaseUi
import cn.oi.klittle.era.comm.KToast
import cn.oi.klittle.era.comm.kpx
import cn.oi.klittle.era.toolbar.KToolbar
import cn.oi.klittle.era.widget.compat.KTextView
import cn.oi.klittle.era.widget.viewpager.KViewPager
import org.jetbrains.anko.*

//fixme 相册图片预览。
open class KPreviewUi : KBaseUi() {

    var toolbar: KToolbar? = null
    var complete: KTextView? = null//请选择，已完成
    var num: KTextView? = null//图片选择个数
    var viewPager: KViewPager? = null
    var previewAdapter: KPreviewPagerAdapter? = null

    var bottomLayout: View? = null//最底部布局

    var data: KLocalMedia? = null//当前选中的实体类

    //设置标题
    fun setTitle(title: String = (KPictureSelector.previewIndex + 1).toString() + "/" + KPictureSelector.previewMeidas?.size) {
        toolbar?.titleTextView?.setText(title)
    }

    fun setTitle(postion: String = (KPictureSelector.previewIndex + 1).toString(), size: String = KPictureSelector.previewMeidas?.size.toString()) {
        toolbar?.titleTextView?.setText(postion + "/" + size)
    }


    //选中个数回调
    fun checkNumCallback(checkNum: Int) {
        num?.setText(checkNum.toString())
        if (checkNum > 0) {
            num?.visibility = View.VISIBLE
            complete?.isSelected = true//已完成
        } else {
            num?.visibility = View.INVISIBLE
            complete?.isSelected = false//请选择
        }
    }

    fun initRightTextView(rightText: KTextView? = toolbar?.rightTextView) {
        if (KPictureSelector.isCheckable) {
            rightText?.apply {
                if (data != null) {
                    txt_selected {
                        text = data?.checkedNum.toString()
                    }
                    isSelected = data!!.isChecked!!
                }
            }
        }
    }

    override fun createView(ctx: Context?): View? {

        data = KPictureSelector.previewMeidas?.get(KPictureSelector.previewIndex)//当前选中的数据

        return ctx?.UI {
            verticalLayout {
                backgroundColor = Color.WHITE
                relativeLayout {
                    viewPager = kviewPager {
                        id = kpx.id("kviewPager")
                        if (Build.VERSION.SDK_INT >= 21) {
                            transitionName = "share_kitem_img"
                        }
                        isScrollEnable = true
                        isFastScrollEnable = false
                        if (previewAdapter == null) {
                            KPictureSelector.previewMeidas?.let {
                                previewAdapter = KPreviewPagerAdapter(it)
                            }
                        }
                        adapter = previewAdapter
                        addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                            override fun onPageScrollStateChanged(state: Int) {

                            }

                            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                            }

                            override fun onPageSelected(position: Int) {
                                //fixme 滑动监听
                                KPictureSelector.previewMeidas?.let {
                                    if (it.size > position) {
                                        data = KPictureSelector.previewMeidas?.get(position)
                                        initRightTextView()
                                        setTitle(postion = (position + 1).toString())
                                    }
                                }
                                previewAdapter?.videoMap?.get(position - 1)?.let {
                                    it?.pause()
                                }
                                previewAdapter?.videoMap?.get(position + 1)?.let {
                                    it?.pause()
                                }
                            }
                        })
                    }.lparams {
                        width = matchParent
                        height = matchParent
                        //above(kpx.id("photo_bottom"))
                    }
                    toolbar = KToolbar(this, getActivity())?.apply {
                        //标题栏背景色
                        contentView?.apply {
                            backgroundColor = Color.parseColor("#0078D7")
                        }
                        //左边返回文本（默认样式自带一个白色的返回图标）
                        leftTextView?.apply {
                        }
                        titleTextView?.apply {
                            textColor = Color.WHITE
                            textSize = kpx.textSizeX(32, false)
                            gravity = Gravity.CENTER
                        }
                        rightTextView?.apply {
                            setText(null)
                        }
                        //判断图片预览是否具备选中能力
                        if (KPictureSelector.isCheckable) {
                            rightTextView?.apply {
                                layoutParams(width = kpx.x(64), height = kpx.x(64), rightMargin = kpx.x(12))
                                radius {
                                    leftMargin = kpx.x(10)
                                    rightMargin = leftMargin
                                    topMargin = leftMargin
                                    bottomMargin = leftMargin
                                    all_radius(kpx.x(200))
                                    strokeColor = Color.WHITE
                                    strokeWidth = kpx.x(2f)
                                }
                                radius_selected {
                                    bg_color = Color.parseColor("#00CAFC")
                                }
                                txt {
                                    textColor = Color.TRANSPARENT
                                    text = ""
                                }
                                txt_selected {
                                    textColor = Color.WHITE
                                    textSize = kpx.textSizeX(26f, false)
                                }
                                initRightTextView(this)//防止初始化的时候为空，所以最好还是传参进去。
                                onClick {
                                    if (data == null) {
                                        return@onClick
                                    }
                                    data?.isChecked = !data!!.isChecked!!
                                    isSelected = data!!.isChecked!!
                                    if (isSelected) {
                                        //选中
                                        var isCover = true//只允许选中一个时，选中会直接覆盖上一次的。
                                        if (KPictureSelector.addNum(data, isCover = isCover, preCheckedPosition = viewPager?.currentItem)) {
                                            txt_selected {
                                                text = data?.checkedNum.toString()//显示当前选中数量
                                            }
                                        } else {
                                            isSelected = false
                                            //你最多可以选择%s张图片
                                            KToast.showInfo(KBaseUi.getString(R.string.kmaxSelectNum, KPictureSelector.maxSelectNum.toString()))
                                        }
                                    } else {
                                        //取消选中
                                        KPictureSelector.reduceNum(data)
                                    }
                                    checkNumCallback(KPictureSelector.currentSelectNum)
                                }
                                leftPadding = 0
                                rightPadding = 0
                                gravity = Gravity.CENTER
                            }
                        } else if (KPictureSelector.isSharedable) {
                            //图片具备分享能行
                            rightTextView?.apply {
                                autoBg {
                                    width = kpx.x(48)
                                    height = kpx.x(48)
                                    autoBgColor = Color.WHITE
                                    autoBg(R.mipmap.kera_share)//分享图标
                                }
                            }
                        } else {
                        }
                    }
                    //fixme 判断预览是否具备图片选中能力
                    if (KPictureSelector.isCheckable) {
                        //底部
                        bottomLayout = relativeLayout {
                            id = kpx.id("photo_bottom")
                            backgroundColor = Color.parseColor("#FAFAFA")
                            num = ktextView {
                                backgroundColor = Color.parseColor("#FA632D")
                                textColor = Color.WHITE
                                textSize = kpx.textSizeX(24, false)
                                gravity = Gravity.CENTER
                                radius {
                                    all_radius(kpx.x(200))
                                }
                                //rightPadding=kpx.x(12)
                                isClickable = true
                            }.lparams {
                                width = kpx.x(42)
                                height = width
                                centerVertically()
                                leftOf(kpx.id("kcomplete"))
                                //rightMargin = kpx.x(12)
                            }
                            complete = ktextView {
                                id = kpx.id("kcomplete")
                                txt {
                                    text = KBaseUi.Companion.getString(R.string.kchoose_photo)//请选择
                                    textSize = kpx.textSizeX(28, false)
                                    textColor = Color.parseColor("#9B9B9B")
                                }
                                txt_selected {
                                    textColor = Color.parseColor("#FA632D")
                                    text = KBaseUi.Companion.getString(R.string.kcomplete)//已完成
                                }
                                gravity = Gravity.CENTER
                                rightPadding = kpx.x(24)
                                leftPadding = kpx.x(12)
                                isClickable = true
                            }.lparams {
                                width = wrapContent
                                //height = wrapContent
                                height = matchParent
                                centerVertically()
                                alignParentRight()
                                //rightMargin = kpx.x(24)
                            }
                        }.lparams {
                            width = matchParent
                            height = kpx.x(88)
                            alignParentBottom()
                        }
                    }
                }
            }
        }?.view
    }

    var animation_top_in: Animation? = null
    var animation_top_out: Animation? = null
    var animation_bottom_in: Animation? = null
    var animation_bottom_out: Animation? = null
    fun toggleView() {
        toolbar?.parentView?.let {
            if (it.visibility == View.GONE) {
                it.visibility = View.VISIBLE
                if (animation_top_in == null) {
                    animation_top_in = AnimationUtils.loadAnimation(it.context, cn.oi.klittle.era.R.anim.kera_layout_slide_in_from_top)
                }
                it.startAnimation(animation_top_in)//顶部进入
            } else {
                if (animation_top_out == null) {
                    animation_top_out = AnimationUtils.loadAnimation(it.context, cn.oi.klittle.era.R.anim.kera_layout_slide_out_to_top)
                    animation_top_out?.setAnimationListener(object :Animation.AnimationListener{
                        override fun onAnimationRepeat(p0: Animation?) {
                        }

                        override fun onAnimationEnd(p0: Animation?) {
                            it.visibility = View.GONE
                        }

                        override fun onAnimationStart(p0: Animation?) {
                        }
                    })
                }
                it.startAnimation(animation_top_out)//顶部退出
            }
        }
        bottomLayout?.let {
            if (it.visibility == View.GONE) {
                it.visibility = View.VISIBLE
                if (animation_bottom_in == null) {
                    animation_bottom_in = AnimationUtils.loadAnimation(it.context, cn.oi.klittle.era.R.anim.kera_layout_slide_in_from_bottom)
                }
                it.startAnimation(animation_bottom_in)//底部部进入
            } else {
                if (animation_bottom_out == null) {
                    animation_bottom_out = AnimationUtils.loadAnimation(it.context, cn.oi.klittle.era.R.anim.kera_layout_slide_out_to_bottom)
                    animation_bottom_out?.setAnimationListener(object :Animation.AnimationListener{
                        override fun onAnimationRepeat(p0: Animation?) {
                        }

                        override fun onAnimationEnd(p0: Animation?) {
                            it.visibility = View.GONE
                        }

                        override fun onAnimationStart(p0: Animation?) {
                        }
                    })
                }
                it.startAnimation(animation_bottom_out)//底部退出
            }
        }
    }

}